<template>
  <app-dialog-form
    :title="`${props.cateId ? '编辑' : '添加'}分类`"
    :confirm="handleSubmit"
    width="500px"
    @closed="handleDialogClosed"
    @open="handleDialogOpen"
  >
    <el-form
      ref="form"
      :model="formData"
      :rules="formRules"
      label-width="90px"
      v-loading="formLoading"
    >
      <el-form-item
        label="上级分类"
        prop="pid"
      >
        <el-select
          v-model="formData.pid"
          placeholder="请选择上级分类"
        >
          <!-- <el-option
            v-for="item in catePidOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          /> -->
          <el-option
            :value="0"
            label="全部"
          />
          <template
            v-for="item in fileCategories"
            :key="item.id"
          >
            <el-option
              :label="item.name"
              :value="item.id"
            >
              <el-icon
                v-if="item.children && item.children.length > 0"
                class="el-icon-arrow-down"
              /> {{ item.name }}
            </el-option>
            <template
              v-if="item.children && item.children.length > 0"
            >
              <el-option
                v-for="item2 in item.children"
                :key="item2.id"
                :label="item2.name"
                :value="item2.id"
              >
                <el-icon
                  class="el-icon-arrow-right"
                />{{ item2.name }}
              </el-option>
            </template>
          </template>
        </el-select>
      </el-form-item>
      <el-form-item
        label="分类名称"
        prop="name"
      >
        <el-input
          v-model="formData.name"
          placeholder="请输入分类名称"
        />
      </el-form-item>
    </el-form>
  </app-dialog-form>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import type { PropType } from 'vue'
import type { IElForm, IFormRule } from '@/types/element-plus'
import type { ISelectOptions } from '@/api/types/form'
import { ElMessage } from 'element-plus'
import { getCreateCategoryRule, saveFileCategory, getEditCategoryRule, updateFileCategory, getFileCategories } from '@/api/file'
import type { FileCategory } from '@/api/types/file'

const props = defineProps({
  cateId: { // 编辑的商品分类 ID
    type: Number as PropType<number | null>,
    default: null
  },
  pid: {
    type: Number,
    default: 0
  }
})

interface EmitsType {
  (e: 'update:cate-id', value: number | null): void
  (e: 'update:pid', value: number | null): void
  (e: 'success'): void
}

const emit = defineEmits<EmitsType>()

const form = ref<IElForm | null>(null)
const formLoading = ref(false)
const formData = ref<{pid: number, name: string}>({
  name: '',
  pid: 0
})
const catePidOptions = ref<ISelectOptions[]>([])

const formRules = ref<IFormRule>({})

formLoading.value = true
const handleDialogOpen = () => {
  formLoading.value = true
  Promise.all([loadFileCategories(), loadCategory()]).finally(() => {
    formLoading.value = false
  })
}
const fileCategories = ref<FileCategory[]>([])

const loadFileCategories = async () => {
  const data = await getFileCategories({ name: '' })
  fileCategories.value = data.list
}

const loadCategory = async () => {
  const rules = props.cateId !== null ? await getEditCategoryRule(props.cateId) : await getCreateCategoryRule({ id: props.pid })
  rules.forEach(item => {
    (formData.value as any)[item.field] = item.value
    formRules.value[item.field] = [{ required: true, message: item.props?.placeholder || item.props?.title || `请选择${item.title}`, trigger: 'blur' }]
    if (item.title === '上级分类') {
      (formData.value as any)[item.field] = Number(item.value)
      if (item.options) catePidOptions.value = item.options
    }
  })
}

const handleDialogClosed = () => {
  emit('update:cate-id', null)
  emit('update:pid', 0)
  form.value?.clearValidate() // 清除验证结果
  form.value?.resetFields() // 清除表单数据
}

const handleSubmit = async () => {
  const valid = await form.value?.validate()
  if (!valid) {
    return
  }
  props.cateId ? await updateFileCategory(props.cateId, formData.value) : await saveFileCategory(formData.value)
  emit('success')
  ElMessage.success('保存成功')
}

</script>

<style lang="scss" scoped>
.el-select {
  width: 100%;
}
</style>
